package com.aj.databases.dao;

import java.sql.SQLException;
import java.util.List;

import android.content.Context;

import com.aj.databases.DatabaseHelper;
import com.aj.databases.entry.Family;
import com.aj.databases.entry.Home;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.RuntimeExceptionDao;

public class FamilyDao {
	public RuntimeExceptionDao<Family, Integer> dao = null;
	private DatabaseHelper helper = null;

	public FamilyDao(Context context) {
		helper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
		dao = helper.getRuntimeExceptionDao(Family.class);
	}

	public List<Family> queryFamilyByCallName(String familyName) {
		try {
			List<Family> familyList = null;
			if (familyName == null) {
				familyList = dao.queryBuilder()
						.orderBy(Family.AGE_STRING, true).where()
						.isNull(Family.CALL_NAME).query();
			} else {
				familyList = dao.queryBuilder()
						.orderBy(Family.AGE_STRING, true).where()
						.eq(Family.CALL_NAME, familyName).query();
			}
			return familyList;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public List<Family> queryFamilyByIsPrivate(Integer isPrivate) {
		try {
			List<Family> familyList = null;
			familyList = dao.queryBuilder().where()
					.eq(Family.IS_PRIVATE, "" + isPrivate).query();
			return familyList;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public Family queryFamilyByUserId(String userid) {
		try {
			List<Family> familyList = null;
			if (userid == null) {
				familyList = dao.queryBuilder().where().isNull(Family.USER_ID)
						.query();
			} else {
				familyList = dao.queryBuilder().where()
						.eq(Family.USER_ID, userid).query();
			}
			if (familyList != null && familyList.size() > 0) {
				return familyList.get(0);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public List<Family> queryFamilyByUserid() {
		try {
			List<Family> familyList = null;
			familyList = dao.queryBuilder().query();
			return familyList;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public List<Family> queryFamilyExistsMine() {
		try {
			List<Family> familyList = null;
			familyList = dao.queryBuilder().where().isNotNull(Family.CALL_NAME)
					.query();
			return familyList;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void deleteAll() {
		dao.executeRawNoArgs("DELETE FROM family");
	}

	public Family insert(Family family) {
		try {
			List<Family> familyList = dao.queryBuilder().where()
					.eq(Home.ID, family.getHome().getId()).and()
					.eq(Family.USER_ID, family.getUserid()).query();
			if (familyList != null && familyList.size() > 0) {
				family.setId(familyList.get(0).getId());
				dao.update(family);
				return family;
			} else {
				return dao.createIfNotExists(family);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
}
